
# -*-coding:utf-8-*-
import redis
from config import basedbname,redis_url,redis_port,redis_pwd

redisdict = {basedbname: '0'}
redisthread = locals()
for redisdbname in redisdict:
    pool = redis.ConnectionPool(host=redis_url, port=redis_port, password=redis_pwd, db=redisdict[redisdbname], decode_responses=True)
    redisthread[redisdbname] = redis.Redis(connection_pool=pool)

# 查询客服是否在线


def selkefuonline(cmpid, serviceid, dbname):
    print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    print(cmpid, serviceid, dbname)
    print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    haveagentonline = 0
    try:
       # print("77777777777777777777777")
       # print(redisthread)
       # print("77777777777777777777777")
        allagent = redisthread[dbname].keys("agent:" + str(cmpid) + ":a"+"*")
        # print(cmpid,serviceid)
        for agent in allagent:
            li = ["services", "online_state", "iscall"]
            alldata = redisthread[dbname].hmget(agent, li)
            print('AAAAAAAAAAAAAAAAAAAAAAA')
            print(alldata)
            print('AAAAAAAAAAAAAAAAAAAAAAA')
            if len(alldata) != 0 and alldata[0] != None:
                for onservice in alldata[0].split(','):
                    print('onservice', onservice, alldata)
                    if str(onservice) == str(serviceid):
                        if str(alldata[1]) == '1' or str(alldata[1]) == '4':
                            if alldata[2] == 'n' or alldata[2] == '':
                                haveagentonline = 1
                                print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
                                print(haveagentonline)
                                print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')
                                break
            if haveagentonline == 1:
                break
        # return 1
        return haveagentonline
    except Exception as e:
        print('++++++++++++++++++')
        print(e)
        print('++++++++++++++++++++++')
        return haveagentonline